package com.next

import com.sun.xml.internal.ws.api.message.Attachment
import grails.converters.JSON
import groovy.json.JsonOutput
import grails.gorm.transactions.Transactional
import org.springframework.security.access.annotation.Secured
import sun.misc.BASE64Decoder

import java.text.SimpleDateFormat

/**
 *
 * 创建日期 2018-03-22
 * 方法功能 “客户端”H5页面的评房、报单、图片上传下载
 **/
@Secured(['permitAll'])
@Transactional(readOnly = true)
class PortalForAppController
{
    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def opportunityService
    def contactService
    def opportunityNotificationService
    def propertyValuationProviderService
    def messageService
    def fileServerService
    def appOpportunityService
    /**
     *
     * 创建日期 2018-03-22
     * 创建人员 班
     * 方法功能 APP对接方法
     **/

    @Transactional
    def login()
    {
        println "******************** portalForApp login *************************"
        println params
        def fullName = params["fullName"]
        def cellphone = params["cellphone"]
        def externalId = params["externalId"]
        //def fullName = "testName"
        //def cellphone = "12345678910"

        if (!fullName)
        {
            println "用户名不能为空"
            redirect(action: "error")
            return
        }

        if (!cellphone)
        {
            println "手机号不能为空"
            redirect(action: "error")
            return
        }
        if (!externalId)
        {
            println "用户ID不能为空"
            redirect(action: "error")
            return
        }

        def user = User.findByUsername("liuming")
        def account = user?.account
        def contact = Contact.findByExternalIdAndType(externalId, "Agent")
        if (!contact)
        {
            contact = new Contact()
        }

        contact.user = user
        contact.account = account
        contact.fullName = fullName
        contact.cellphone = cellphone
        contact.externalId = externalId
        //contact.idNumber = idNumber
        //contact.city = City.findByCode(cityCode)

        contact.type = "Agent"

        if (contact.validate())
        {
            contact.save flush: true
        } else
        {
            println contact.errors
            redirect(action: "error")
            return
        }

        respond contact, view: "welcome"

    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 微信报单功能
     **/
    @Transactional
    def update2(Opportunity opportunity)
    {
        if (!opportunity?.contact)
        {
            if (!params["openId"])
            {
                flash.message = message(code: "报单失败，请稍后重试")
                respond opportunity, view: 'show2'
                return
            } else
            {
                def contact = ContactLoginCertificate.findByExternalId(params["openId"])?.contact
                opportunity.contact = contact
                opportunity.status = "Pending"
                opportunity.account = contact?.user?.account
                opportunity.user = contact?.user
                opportunity.loanApplicationProcessType = LoanApplicationProcessType.findByName("直接报单")
            }
        }

        // 借款人信息
        Contact loanContact = new Contact()
        loanContact.fullName = opportunity.fullName
        loanContact.maritalStatus = opportunity.maritalStatus
        loanContact.cellphone = opportunity.cellphone
        loanContact.user = opportunity?.contact?.user
        loanContact.account = opportunity?.contact?.account
        loanContact.level = ContactLevel.findByName("B")
        loanContact.type = "Client"
        loanContact.save flush: true

        // 抵押人信息
        Contact mortgageContact = null
        if (params['myGroup'] == '0')
        {
            mortgageContact = new Contact()
            mortgageContact.fullName = "抵押人姓名"
            mortgageContact.maritalStatus = params["mortgagorMaritalStatus"]
            mortgageContact.user = opportunity?.contact?.user
            mortgageContact.account = opportunity?.contact?.account
            mortgageContact.save flush: true
        }

        Integer protectDays = 10
        if (opportunity.cellphone)
        {
            protectDays += 5
        }
        Date protectionStartTime = new java.util.Date()
        opportunity.protectionStartTime = protectionStartTime
        opportunity.protectionEndTime = protectionStartTime + protectDays
        opportunity.stage = OpportunityStage.findByCode("04")
        opportunity.createdDate = new Date()
        opportunity.modifiedDate = new Date()
        opportunity.lender = loanContact
        if (opportunity.validate())
        {
            opportunity.save flush: true
        } else
        {
            println opportunity.errors
        }

        def fileNames = params["fileNames"]
        def imagList = fileNames?.split(",")
        if (imagList.size() > 0)
        {
            imagList.each {
                def attachmentType = it.split(":")[0]
                def fileName = it.split(":")[1]
                def attachment = new Attachments()
                attachment.fileName = "http://s27.cindata.com/fs/static/images/${fileName}"
                attachment.type = AttachmentType.find("from AttachmentType where name = '${attachmentType}'")
                attachment.opportunity = opportunity
                attachment.contact = opportunity?.contact
                if (attachment.validate())
                {
                    attachment.save flush: true
                } else
                {
                    attachment.errors.each {
                        println it
                    }
                }
            }
        } else
        {
            flash.message = message(code: "图片上传失败，请稍后重试")
            respond opportunity, view: 'show2'
            return
        }

        OpportunityContact loanOpportunityContact = new OpportunityContact()
        loanOpportunityContact.opportunity = opportunity
        loanOpportunityContact.contact = loanContact
        loanOpportunityContact.type = OpportunityContactType.findByName("借款人")
        loanOpportunityContact.save flush: true

        if (mortgageContact)
        {
            OpportunityContact mortgageOpportunityContact = new OpportunityContact()
            mortgageOpportunityContact.opportunity = opportunity
            mortgageOpportunityContact.contact = mortgageContact
            mortgageOpportunityContact.type = OpportunityContactType.findByName("抵押人")
            mortgageOpportunityContact.save flush: true
        }

        //订单初始化
        opportunityService.initOpportunity(opportunity)

        redirect(action: "opportunitySuccessful", id: opportunity.id)
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 根据微信公众平台返回图片的serverId拉取图片，并存储到图片服务器
     **/
    @Secured('permitAll')
    @Transactional
    def getImgServerId()
    {
        def marialFile = "借款人身份证," + params["marialFile"]
        def maritalReverseFile = "借款人身份证," + params["maritalReverseFile"]
        def spouseFile = "借款人配偶身份证," + params["spouseFile"]
        def spouseReverseFile = "借款人配偶身份证," + params["spouseReverseFile"]
        def mortgagorFile = "抵押人身份证," + params["mortgagorFile"]
        def mortgagorReverseFile = "抵押人身份证," + params["mortgagorReverseFile"]
        def mortgagorSpouseFile = "抵押人配偶身份证," + params["mortgagorSpouseFile"]
        def mortgagorSpouseReverseFile = "抵押人配偶身份证," + params["mortgagorSpouseReverseFile"]
        def properties = params["properties"]

        def list = [marialFile, maritalReverseFile]
        if (params["spouseFile"])
        {
            list.add(spouseFile)
            list.add(spouseReverseFile)
        }
        if (params["mortgagorFile"])
        {
            list.add(mortgagorFile)
            list.add(mortgagorReverseFile)
        }
        if (params["mortgagorSpouseFile"])
        {
            list.add(mortgagorSpouseFile)
            list.add(mortgagorSpouseReverseFile)
        }
        if (!properties)
        {
            flash.message = message(code: "请上传房产证")
            respond opportunity, view: 'upload'
            return
        }
        def propertiesList = properties.split(",")
        if (propertiesList.size() > 0)
        {
            propertiesList.each {
                list.add("房产证," + it)
            }
        }

        def fileNameList = []
        def webrootDir = servletContext.getRealPath("/")
        def accessToken = params["accessToken"]
        list.each {
            def serverId = it.split(",")[-1]
            def fileName = opportunityService.uploadImage(webrootDir, accessToken, serverId)
            if (fileName != 0)
            {
                def attachmentType = it.split(",")[0]
                fileNameList.add("${attachmentType}:${fileName}")
            } else
            {
                flash.message = message(code: "图片上传失败，请稍后重试")
                respond opportunity, view: 'show2'
                return
            }
        }

        if (fileNameList.size() > 0)
        {
            println "Ajax请求返回图片相关信息（新版）："
            render([status: "success", fileNameList: fileNameList] as JSON)
        } else
        {
            render([status: "error", errorMsg: "图片上传失败，请稍后重试"] as JSON)
        }
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 报单成功页跳转
     **/
    @Secured('permitAll')
    def opportunitySuccessful(Opportunity opportunity)
    {
        respond opportunity
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 订单详情页跳转
     **/
    @Secured('permitAll')
    def show(Opportunity opportunity)
    {
        def house = House.findByOpportunity(opportunity)
        respond opportunity, model: [house: house], view: "show"
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 报单页跳转
     **/
    @Secured('permitAll')
    @Transactional
    def show2()
    {
        println " show2   params:  " + params

        // 评房报单
        def contact = params['contact']
        def collateralId = params['collateralId']
        def opportunity = Opportunity.findById(params["id"])
        opportunity.loanApplicationProcessType = LoanApplicationProcessType.findByName("先评房再报单")
        if (opportunity?.contact?.city?.id == 1)
        {
            respond opportunity
        } else
        {
            redirect(action: "show4", id: params["id"], params: [contact: contact, collateralId: collateralId])
        }

    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 验证订单是否处于保护期
     **/
    @Secured(['permitAll'])
    @Transactional
    def verifyProtectDay()
    {
        def requestedAmount = params["requestedAmount"]
        def loanDuration = params["loanDuration"]
        def fullName = params["fullName"]
        if (Opportunity.findByFullNameAndRequestedAmountAndLoanDuration(fullName, Integer.parseInt(requestedAmount), Double.parseDouble(loanDuration)))
        {
            render([status: "success", flag: true] as JSON)
        } else
        {
            render([status: "success", flag: false] as JSON)
        }
    }

    /**
     *
     * 创建日期 2018-03-22
     * 创建人员 班
     * 方法功能 评房功能，页面一跳转
     **/
    @Transactional
    def create2Step1()
    {
        println "create2Step1  params:     " + params["contact"]
        def contactId = params["contact"]
        def cityList = City.list()
        if (cityList.size() == 0)
        {
            flash.message = message(code: "暂无开放城市")
        }

        def house = new House()
        def contact = Contact.findById(contactId)
        respond house, model: [cityList: cityList, contactId: contactId, contact: contact]
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 评房功能，页面二跳转，查询区县功能
     **/
    @Secured(['permitAll'])
    @Transactional
    def create2Step2(House house)
    {
        println "create2Step2  params:     " + params
        def projectNameList = []
        def contactId = params['contactId']
        def result = propertyValuationProviderService.searchProjectName(house?.city?.code, District.findByName(house?.district)?.code, house?.projectName)
        //        println "result:  " + result
        if (result != 0)
        {
            if (result['code'] != "0")
            {
                if (result['code'] in ['-1', '1', '2', '3'])
                {
                    //                    def errors = [errorCode: 4666, errorMessage: result['message']]
                    flash.message = message(code: result['message'])
                    //                    render JsonOutput.toJson(errors), status: 400
                    respond house, model: [projectNameList: projectNameList, contactId: contactId]
                }
            } else
            {
                def newList = []
                def dataLength = result['data'].size()
                if (dataLength != 0)
                {
                    for (
                        def i = 0;
                        i < dataLength;
                        i++)
                    {
                        def communityMap = [:]
                        communityMap["communityName"] = result['data'][i].communityName
                        communityMap["communityId"] = result['data'][i].communityId
                        communityMap["address"] = result['data'][i].address
                        newList.add(communityMap)
                    }
                }

                respond house, model: [projectNameList: newList, contactId: params["contactId"], params2: params]
            }
        } else
        {
            flash.message = message(code: "网络不稳定，请稍后重试")
            redirect(action: "create2Step1", id: house.id, params: [contact: contactId])
        }

    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 评房功能，页面三跳转
     **/
    @Secured(['permitAll'])
    @Transactional
    def create2Step3(House house)
    {
        println "create2Step3  params:     " + params
        def houseTypeList1 = HouseType.list()
        def houseTypeList = []
        houseTypeList1.each {
            if (!(it?.name in ["独栋", "联排", "双拼", "叠拼"]))
            {
                houseTypeList.add(it?.name)
            }
        }
        def assetTypeList1 = AssetType.list()
        def assetTypeList = []
        assetTypeList1.each {
            if (!(it?.name in ["住宅", "央产房", "优惠价房改房", "标准价房改房", "军产房", "校产房", "其他", "成本价房改房"]))
            {
                assetTypeList.add(it?.name)
            }
        }
        def projectName2 = params['projectName2']
        respond house, model: [contactId: params["contactId"], houseTypeList: houseTypeList, assetTypeList: assetTypeList, projectName2: projectName2], view: "create2Step3"
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 评房功能，询值
     **/
    @Secured(['permitAll'])
    @Transactional
    def create2Step4Save(House house)
    {

        println "create2Step4Save   params:   " + params
        def opportunity = new Opportunity()
        def contactId = params["contactId"]
        def contact = Contact.findById(contactId)
        opportunity.contact = contact

        def apiUrl = CreditReportProvider.findByCode("PV")?.apiUrl
        house.status = params["status"]
        //        house.externalId = params["externalId"]

        def unitPrice = params["unitPrice"]
        if (!unitPrice)
        {
            unitPrice = '0'
        }
        house.unitPrice = Double.parseDouble(unitPrice)
        house.totalPrice = Double.parseDouble(unitPrice) * house.area
        // 楼阁、跃层
        if (house.atticArea > 0)
        {
            house.totalPrice += Double.parseDouble(unitPrice) * house.atticArea / 2
        }

        opportunity.loanAmount = house.totalPrice
        opportunity.unitPrice = house.unitPrice
        if (house?.status == "Completed")
        {
            opportunity.stage = OpportunityStage.findByCode("02")
        } else
        {
            opportunity.stage = OpportunityStage.findByCode("15")
        }

        // 订单默认分配给支持经理人
        //        def user = User.findByCellphone(opportunity?.contact?.userCode)
        def user = User.findById(opportunity?.contact?.user?.id)
        opportunity.user = user
        opportunity.account = user?.account


        if (opportunity.validate())
        {
            opportunity.save flush: true
            //            if (opportunity?.stage?.code == '02')
            //            {
            //                messageService.sendMessage2(apiUrl, opportunity?.contact?.userCode, "【Default】您的经纪人 " + opportunity?.contact?.fullName + "（" + opportunity?.contact?.cellphone + "） 有评房成功订单（" + opportunity?.serialNumber + "），请及时关注跟进！")
            //            }
        } else
        {
            opportunity.errors.each {
                println it
            }
        }
        house.opportunity = opportunity
        house.requestStartTime = new Date()
        if (house.validate())
        {
            house.save()
        } else
        {
            println house.errors
        }

        //订单初始化
        opportunityService.initOpportunity(opportunity)

        redirect(action: "create2Step4", id: house.id, params: [contactId: contactId])
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 评房功能，询值成功
     **/
    @Secured(['permitAll'])
    @Transactional
    def create2Step4()
    {
        def house = House.findById(params['id'])
        println "create2Step4 params :   " + params
        respond house, model: [contactId: params["contactId"], house: house]
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 将图片上传到微信公众平台，该方法用于获取微信上传接口的参数，accessToken、nonceStr、signature、timestamp
     **/
    @Secured(['permitAll'])
    @Transactional
    def upload(Opportunity opportunity)
    {
        def accessToken = opportunityService.getAccessToken()
        if (!accessToken)
        {
            flash.message = message(code: "获取access_token失败，请稍后重试")
            respond opportunity, view: 'upload'
            return
        }

        def ticket = opportunityService.getTicket(accessToken)
        if (!ticket)
        {
            flash.message = message(code: "获取jsapi_ticket失败，请稍后重试")
            respond new Opportunity(), view: 'upload'
            return
        }

        def nonceStr = UUID.randomUUID().toString()
        def time = (System.currentTimeMillis() / 1000).toString()
        def timestamp = time.substring(0, time.lastIndexOf("."))
        def url = request.getRequestURL()
        def signature = opportunityService.getSignature(ticket, nonceStr, timestamp, url.toString())

        respond opportunity, model: [nonceStr: nonceStr, timestamp: timestamp, signature: signature, accessToken: accessToken], view: "upload"
    }

    /**
     *
     * 创建日期 2018-03-22
     * 创建人员 fc
     * 方法功能 精准估值功能，页面一跳转
     **/
    @Transactional
    def create3Step1()
    {
        def contactId = params["contact"]
        def cityList = City.list()
        if (cityList.size() == 0)
        {
            flash.message = message(code: "暂无开放城市")
        }

        def attachmentType = AttachmentType.findByName("房产证")
        def house = new House()
        respond house, model: [cityList: cityList, contactId: contactId, attachmentType: attachmentType]
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 通过城市获取小区
     **/
    @Secured(['permitAll'])
    @Transactional
    def getDistrictByCity()
    {
        def city = params["city"]
        def list = []
        if (city)
        {
            list = District.findAllByCity(City.findById(city))
        }

        def districtList = []
        if (list)
        {
            list.each {
                districtList.add(it?.name)
            }
        }
        render([status: "success", districtList: districtList] as JSON)
        return
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 微信复评功能上传图片，该方法用于获取微信上传接口的参数，accessToken、nonceStr、signature、timestamp
     **/
    @Secured(['permitAll'])
    @Transactional
    def suggest(House house)
    {
        def isreturn = params["isreturn"]
        def backUrl = params['backUrl']

        println "backUrl:" + backUrl
        respond house, model: [isreturn: isreturn, backUrl: backUrl], view: 'suggest'
        return
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 微信复评功能
     **/
    @Secured(['permitAll'])
    @Transactional
    def suggestSave(House house)
    {
        if (house == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (house.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            render([status: "error", errorMsg: house.errors] as JSON)
            // respond house.errors, view: 'suggest'
            return
        }

        house.status = "Pending"
        if (house.validate())
        {
            house.save flush: true
        } else
        {
            println house.errors
        }
        def opportunity = house.opportunity
        def attachmentsList = []
        def fileNames = params["fileNames"]
        if (fileNames)
        {
            def fileNamesList = fileNames.split(",")
            if (fileNamesList.size() > 0)
            {
                def attachment = new Attachments()

                attachment.fileName = params["fileNames"]
                attachment.thumbnailUrl = params["fileNames"]
                attachment.opportunity = house?.opportunity
                attachment.contact = house?.opportunity?.contact
                attachment.type = AttachmentType.findById(params["propertyType"])
                if (attachment.validate())
                {
                    attachment.save flush: true
                } else
                {
                    println attachment.errors
                }

                def suggestAttachment = [:]
                suggestAttachment['attachmentType'] = attachment.type
                suggestAttachment['fileName'] = attachment.fileName
                attachmentsList.add(suggestAttachment)
            }
        }

        // 微信复评功能
        def result = [:]
        result['reasonOfPriceAdjustment'] = house?.reasonOfPriceAdjustment
        result['appliedTotalPrice'] = house?.appliedTotalPrice
        result['attachments'] = attachmentsList
        result['externalId'] = house.externalId

        println "微信复评入参:"
        println result

        house.requestEndTime = new Date()
        //house.unitPrice = unitPrice.toDouble()
        house.totalPrice = house.unitPrice * house.area
        house.status = "Completed"
        if (house.validate())
        {
            house.save flush: true
        } else
        {
            println house.errors
        }
        if (opportunity)
        {
            //opportunity.unitPrice = unitPrice.toDouble()
            opportunity.loanAmount = house.unitPrice * house.area
            // 楼阁、跃层
            if (house.atticArea > 0)
            {
                opportunity.loanAmount += house.unitPrice * house.atticArea / 2
            }
            // opportunity.stage = OpportunityStage.findByCode("02")
            if (opportunity.validate())
            {
                opportunity.save flush: true
            } else
            {
                println opportunity.errors
            }

        }

        //redirect(action: "suggest", id: house.id, params: [/** suggestMessage: "复评价格为" + opportunity.loanAmount + "万元", **/
        //isreturn: 1])
        // redirect(action: "suggestSuccess", id: house.id, params: [/** suggestMessage: "复评价格为" + opportunity.loanAmount + "万元", **/
        //         isreturn: 1])
        render([status: "success", contact: opportunity?.contact?.id] as JSON)
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 微信复评功能 根据微信公众平台返回图片的serverId拉取图片，并存储到图片服务器
     **/
    @Secured('permitAll')
    @Transactional
    def getEvaluateImgServerId()
    {
        def attachmentsList = []
        def evaluateFiles = params["evaluateFiles"]
        def accessToken = params["accessToken"]
        def webrootDir = servletContext.getRealPath("/")
        def evaluateFilesList = evaluateFiles.split(",")
        if (evaluateFilesList.size() > 0)
        {
            evaluateFilesList.each {
                def fileName = opportunityService.uploadImage(webrootDir, accessToken, it)
                if (fileName != 0)
                {
                    attachmentsList.add("估值附回材料:${fileName}")
                } else
                {
                    render([status: "error", errorMsg: "图片获取失败，请稍后重试"] as JSON)
                }
            }
        }

        render([status: "success", fileNameList: attachmentsList] as JSON)
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 微信复评成功跳转
     **/
    @Secured(['permitAll'])
    @Transactional
    def suggestSuccess(House house)
    {
        respond house, model: [suggestMessage: params.suggestMessage]
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 根据区县信息查询房屋价格，询值功能
     **/
    @Secured(['permitAll'])
    @Transactional
    def queryPrice()
    {
        def house = new House()
        house.city = City.findById(params['city'])
        house.district = params['district']
        house.projectName = params['projectName']
        house.building = Integer.parseInt(params['building'])
        house.unit = Integer.parseInt(params['unit'])
        house.floor = params['floor']
        house.roomNumber = params['roomNumber']
        house.totalFloor = params['totalFloor']
        house.area = Double.parseDouble(params['area'])
        house.address = params['address']
        house.orientation = params['orientation']
        house.houseType = params['houseType']
        house.specialFactors = params['specialFactors']
        house.assetType = params['assetType']
        house.appliedTotalPrice = Double.parseDouble(params['appliedTotalPrice'])
        def atticArea = params['atticArea']
        if (atticArea)
        {
            house.atticArea = Double.parseDouble(atticArea)
        } else
        {
            house.atticArea = 0
        }

        def price = propertyValuationProviderService.appQueryPrice(house)
        if (price != 0)
        {
            println "询值结果："
            println price
            if (price['code'] in ['-1', '1', '2', '3'])
            {
                render([status: "error", errorMsg: price['message'], collateralStatus: "Failed"] as JSON)
            }
            def status = "Completed"
            def unitprice = price['unitprice']
            def saleprice = price['saleprice']
            render([status: "success", price: price, collateralStatus: status, unitprice: unitprice, saleprice: saleprice] as JSON)
        } else
        {
            render([status: "error", errorMsg: "询价失败，请稍后重试", collateralStatus: "Failed"] as JSON)
        }
    }

    // ****************************供老版保单页面使用*****************************

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 报单页跳转 旧版（需要录入借款人、借款人配偶，抵押人、抵押人配偶信息）
     **/
    @Secured('permitAll')
    @Transactional
    def show4(Opportunity opportunity)
    {
        println "show4  params:  " + params
        def collateralId = params['collateralId']
        respond opportunity, model: [collateralId: collateralId, contact: params['contact']]
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 订单保护期时长计算 旧版（根据借款人、借款人配偶、抵押人、抵押人配偶手机号）
     **/
    @Secured(['permitAll'])
    @Transactional
    def getProtectTime()
    {
        Integer protectDays = 10
        if (params["cellphone"])
        {
            protectDays += 5
        }
        if (params["spouseCellphone"])
        {
            protectDays += 5
        }
        if (params["mortgagorCellphone"])
        {
            protectDays += 5
        }
        if (params["mortgagorSpouseCellphone"])
        {
            protectDays += 5
        }

        render([status: "success", protectDays: protectDays] as JSON)
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 验证订单是否处于保护期 旧版（根据借款人身份证验证）
     **/
    @Secured(['permitAll'])
    @Transactional
    def verifyProtectDay2()
    {
        def idNumber = params["idNumber"]
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        def opportunity = Opportunity.find("from Opportunity as c where c.idNumber = '${idNumber}' and c.stage not in ('01', '02', '11') and c.status = 'Pending' and c.protectionEndTime > '" + format.format(new Date()) + "'")
        if (opportunity)
        {
            render([status: "success", flag: true] as JSON)
        } else
        {
            render([status: "success", flag: false] as JSON)
        }
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 将图片上传到微信公众平台，该方法用于获取微信上传接口的参数，accessToken、nonceStr、signature、timestamp 旧版
     **/
    @Secured(['permitAll'])
    @Transactional
    def upload2(Opportunity opportunity)
    {
        println "upload2 params:      " + params
        def imgType = params['imgType']
        def attachmentType = AttachmentType.findByName(imgType)
        def propertyImgCount = Attachments.executeQuery("select count(id) from Attachments where opportunity.id=${opportunity?.id} and type.id=${attachmentType.id}")

        respond opportunity, model: [params: params, propertyImgCount: propertyImgCount[0], collateralId: params['collateralId']], view: "upload2"
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 根据微信公众平台返回图片的serverId拉取图片，并存储到图片服务器 旧版
     **/
    @Secured('permitAll')
    @Transactional
    def getImgServerId2()
    {
        def marialFile = "借款人身份证," + params["marialFile"]
        def maritalReverseFile = "借款人身份证," + params["maritalReverseFile"]
        def spouseFile = "借款人配偶身份证," + params["spouseFile"]
        def spouseReverseFile = "借款人配偶身份证," + params["spouseReverseFile"]
        def mortgagorFile = "抵押人身份证," + params["mortgagorFile"]
        def mortgagorReverseFile = "抵押人身份证," + params["mortgagorReverseFile"]
        def mortgagorSpouseFile = "抵押人配偶身份证," + params["mortgagorSpouseFile"]
        def mortgagorSpouseReverseFile = "抵押人配偶身份证," + params["mortgagorSpouseReverseFile"]
        def properties = params["properties"]

        def list = [marialFile, maritalReverseFile]
        if (params["spouseFile"])
        {
            list.add(spouseFile)
            list.add(spouseReverseFile)
        }
        if (params["mortgagorFile"])
        {
            list.add(mortgagorFile)
            list.add(mortgagorReverseFile)
        }
        if (params["mortgagorSpouseFile"])
        {
            list.add(mortgagorSpouseFile)
            list.add(mortgagorSpouseReverseFile)
        }
        if (!properties)
        {
            flash.message = message(code: "请上传房产证")
            respond opportunity, view: 'upload2'
            return
        }
        def propertiesList = properties.split(",")
        if (propertiesList.size() > 0)
        {
            propertiesList.each {
                list.add("房产证," + it)
            }
        }

        def fileNameList = []
        def webrootDir = servletContext.getRealPath("/")
        def accessToken = params["accessToken"]
        list.each {
            def serverId = it.split(",")[-1]
            def fileName = opportunityService.uploadImage(webrootDir, accessToken, serverId)
            if (fileName != 0)
            {
                def attachmentType = it.split(",")[0]
                fileNameList.add("${attachmentType}:${fileName}")
            } else
            {
                flash.message = message(code: "图片上传失败，请稍后重试")
                respond opportunity, view: 'show4'
                return
            }
        }

        if (fileNameList.size() > 0)
        {
            println "Ajax请求返回图片相关信息（老版）："
            println fileNameList
            render([status: "success", fileNameList: fileNameList] as JSON)
        } else
        {
            render([status: "error", errorMsg: "图片上传失败，请稍后重试"] as JSON)
        }
    }

    /**
     *
     * 创建日期 2017-04-21
     * 创建人员 张成远
     * 方法功能 报单功能 旧版
     **/
    @Secured('permitAll')
    @Transactional
    def update3(Opportunity opportunity)
    {
        println "update3 params:   " + params
        if (opportunity == null)
        {
            transactionStatus.setRollbackOnly()
            notFound()
            return
        }

        if (opportunity.hasErrors())
        {
            transactionStatus.setRollbackOnly()
            respond opportunity.errors, view: 'show4'
            return
        }

        def idNumber = params["idNumberTemp"]
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        def opportunity1 = Opportunity.find("from Opportunity as c where c.idNumber = '${idNumber}' and c.stage not in ('01', '02', '11') and c.status = 'Pending' and c.protectionEndTime > '" + format.format(new Date()) + "'")
        if (opportunity1)
        {
            // 借款人处于保护期，不可以报单
            flash.message = message(code: 'opportunity.inProjectTime.message')
            redirect(action: "show4", id: opportunity.id)
        } else
        {
            Integer protectDays = 10
            if (params["cellphone"])
            {
                protectDays += 5
            }
            if (params["spouseCellphone"])
            {
                protectDays += 5
            }
            if (params["mortgagorCellphone"])
            {
                protectDays += 5
            }
            if (params["mortgagorSpouseCellphone"])
            {
                protectDays += 5
            }

            // 保护期
            Date protectionStartTime = new java.util.Date()
            opportunity.protectionStartTime = protectionStartTime
            opportunity.protectionEndTime = protectionStartTime + protectDays
            opportunity.stage = OpportunityStage.findByCode("04")
            opportunity.modifiedDate = new Date()
            opportunity.idNumber = params["idNumberTemp"]

            // 保存图片信息
            def fileNames = params["fileNames"]
            println "fileNames:  " + fileNames
            //            if (imagList.size() > 0)
            if (fileNames)
            {
                def imagList = fileNames?.split(",")
                for (
                    def i = 1;
                    i < imagList.size();
                    i++)
                {
                    //                    println "imagList[i]:  "+imagList[i]
                    def fileName = imagList[i].split("&")[0]
                    def attachmentType = imagList[i].split("&")[2]
                    def description = imagList[i].split("&")[1]
                    def attachment = new Attachments()
                    attachment.fileName = fileName
                    attachment.thumbnailUrl = fileName
                    attachment.type = AttachmentType.findById(attachmentType)
                    attachment.opportunity = opportunity
                    attachment.contact = opportunity?.contact
                    attachment.description = description
                    if (attachment.validate())
                    {
                        attachment.save flush: true
                    } else
                    {
                        attachment.errors.each {
                            println it
                        }
                    }
                }
            } else
            {
                transactionStatus.setRollbackOnly()
                flash.message = message(code: "图片上传失败，请稍后重试")
                //                respond opportunity, view: 'Show4'
                redirect(action: "show4", id: opportunity.id)
                return
            }
            if (opportunity.validate())
            {
                opportunity.save flush: true
            } else
            {
                println opportunity.errors
            }

            // 借款人信息
            if (opportunity?.idNumber)
            {
                opportunityService.addContacts(opportunity?.fullName, opportunity?.idNumber, opportunity?.cellphone, opportunity?.maritalStatus, "借款人", opportunity)
            }
            // 借款人配偶信息
            String spouseIdNumber = params["spouseIdNumber"]
            if (spouseIdNumber)
            {
                opportunityService.addContacts(params["spouseFullName"], params["spouseIdNumber"], params["spouseCellphone"], "已婚", "借款人配偶", opportunity)
            }
            // 抵押人信息
            String mortgagorIdNumber = params["mortgagorIdNumber"]
            if (mortgagorIdNumber)
            {
                opportunityService.addContacts(params["mortgagorFullName"], params["mortgagorIdNumber"], params["mortgagorCellphone"], params["mortgagorMaritalStatus"], "抵押人", opportunity)
            }
            // 抵押人配偶信息
            String mortgagorSpouseIdNumber = params["mortgagorSpouseIdNumber"]
            if (mortgagorSpouseIdNumber)
            {
                opportunityService.addContacts(params["mortgagorSpouseFullName"], params["mortgagorSpouseIdNumber"], params["mortgagorSpouseCellphone"], "已婚", "抵押人配偶", opportunity)
            }

            opportunityService.assignToClient(opportunity)

            //订单初始化
            opportunityService.initOpportunity(opportunity)

            // redirect(action: "show", id: opportunity.id)
            redirect(action: "opportunitySuccessful", id: opportunity.id)
        }
    }

    /**
     *
     * 创建日期 2018-03-23
     * 创建人员 fc
     * 方法功能 精准估值功能，页面二跳转
     **/
    @Transactional
    @Secured('permitAll')
    def create3Step2()
    {
        def contactIdparams = params["x:contactId"]
        Contact contact = Contact.findById(contactIdparams)

        def city = City.findById(params["x:city"])

        if (!city)
        {
            flash.message = "请选择所在城市"
            redirect(action: 'create3Step1', params: [contactId: contact.id])
            return
        }
        //获取文件名称
        def returnFlag = true

        println "######新建房产信息###########"

        House house = new House()
        house.requestStartTime = new Date()
        house.city = city
        house.district = "未知"
        house.projectName = "未知"
        house.building = "未知"
        house.orientation = "未知"
        house.unit = "未知"
        house.atticArea = 0
        house.floor = "未知"
        house.roomNumber = "未知"
        house.totalFloor = "未知"
        house.area = 0
        house.address = "未知"
        house.houseType = "未知"
        house.assetType = "未知"
        house.specialFactors = "未知"
        house.appliedTotalPrice = 0
        //new Opportunity start
        def opportunity = new Opportunity()
        opportunity.contact = contact
        opportunity.user = contact?.user
        opportunity.account = contact?.user?.account
        opportunity.save()

        house.opportunity = opportunity
        //new Opportunity end

        println "######新建订单信息###########"
        opportunity.loanAmount = 0
        opportunity.stage = OpportunityStage.findByCode("15")
        opportunity.unitPrice = 0
        opportunity.loanApplicationProcessType = LoanApplicationProcessType.findByName("直接报单")
        opportunity.valuationType = "accuracy"

        if (opportunity.validate())
        {
            opportunity.save flush: true
        } else
        {
            println opportunity.errors
        }

        println "######新建的opportunity.id###########"
        println opportunity.id

        house.unitPrice = 0
        house.totalPrice = 0
        house.status = "Pending"

        if (house.validate())
        {
            house.save flush: true
        } else
        {
            println house.errors
        }

        println "######订单初始化###########"
        appOpportunityService.initOpportunity(opportunity)

        def result1 = [:]
        result1['reasonOfPriceAdjustment'] = "unknown"
        result1['appliedTotalPrice'] = 0

        def simple = [:]
        simple['attachmentType'] = '1'

        //def attachment = Attachments.findById(params["fileid"])
        def attachment = new Attachments()

        attachment.fileName = params["fileNames"]
        //attachment.fileUrl = fileUrl
        attachment.opportunity = opportunity
        attachment.type = AttachmentType.findById(params["propertyType"])

        if (attachment.validate())
        {
            println "fileName" + attachment.fileName
            println "fileUrl" + attachment.fileUrl

            attachment.save flush: true
            //ats.add(simple)
        } else
        {
            returnFlag = false
            println attachment.errors
            return
        }

        //pictUrl += fileUrl
        //pictUrl += ";"

        //result1['attachments'] = ats
        result1['externalId'] = house.externalId

        def resultJson = ""
        println "result1:" + result1
        String param1 = result1 as JSON
        println param1
        // resultJson = propertyValuationProviderService.suggestSubmmit1(param)
        resultJson = propertyValuationProviderService.appQueryPrice1(house, attachment.thumbnailUrl)

        if (!resultJson)
        {
            flash.message = "调用评房反馈服务上传图片失败，请稍后重试"
            redirect(action: 'create3Step1', params: [contactId: contact.id])
            return
        } else
        {
            if (resultJson['code'] in ['-1', '1', '2', '3'])
            {
                flash.message = resultJson['message']
                redirect(action: 'create3Step1', params: [contactId: contact.id])
                redirect(action: 'create3Step1')
                return
            }

            def externalId = resultJson['evaluateCode']?.toString()
            house.externalId = externalId
            house.save flush: true

            println "######精确估值结束###########"
        }

        respond opportunity
        return
    }

    /**
     *
     * 创建日期 2018-03-23
     * 创建人员 fc
     * 方法功能 精准估值功能，页面二跳转
     **/
    @Secured('permitAll')
    @Transactional
    def CallbackByQiniuPrecise()
    {
        println "********** 精准估值 *************"

        println "*********************** callbackByQiniu  ****************************"
        println params
        def json = request.JSON
        println "json:" + json
        /************************七牛服务器回调函数时返回json对象*****************************/
        String contactId = json["contactId"]
        String attachmentType = json["type"]
        String fileName = json["fileName"]
        String description = json['description']
        def city = json['city']
        /****************************end*************************/
        /***********************自定义方法返回值使用params*****************************/
        //String contactId = params["contactId"]
        //String attachmentType = params["type"]
        //String fileName = params["fileName"]
        //String description = params['description']
        //def city = params['city']
        /****************************end*************************/


        def attachment = new Attachments()
        attachment.fileName = "http://p66wk755l.bkt.clouddn.com/" + fileName
        attachment.thumbnailUrl = "http://p66wk755l.bkt.clouddn.com/" + fileName
        attachment.type = AttachmentType.findById(attachmentType)
        attachment.description = description.split('\\.')[0]

        println "*********************** end callbackByQiniu  ****************************"

        if (attachment.validate())
        {

            def files = []
            def sfile = [:]
            def o = [:]
            sfile['thumbnailUrl'] = attachment.thumbnailUrl
            sfile['name'] = description

            attachment.save flush: true

            sfile['fileid'] = attachment.id

            files.add(sfile)
            o['files'] = files

            render o as JSON
            return
        } else
        {
            println attachment.errors
            render([status: "error", errorMsg: "attachments save error"] as JSON)
            return
        }
    }

    /**
     *
     * 创建日期 2018-03-27
     * 创建人员 fc
     * 方法功能 评估记录跳转
     **/
    @Secured('permitAll')
    @Transactional
    def indexOfOpportunity()
    {
        def contactId = params['contact']
        def contact = Contact.findById(contactId)
        //if (!contact)
        //{
        //flash.message="用户登录失效，请重新登陆"
        //redirect(action: "login")
        //return
        //}

        def stageStatus = params["stage"]
        //if (!contact)
        //{
        //redirect(action: "login")
        //return
        //}
        def opportunity = []
        if ("allItems" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.stage.code <> '02' and c.stage.code <> '15' order by createdDate desc")
        }
        if ("alreadyPF" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.stage.code in ('02', '15') and c.status <> 'Failed' order by createdDate desc")
        }
        if ("waitSH" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.stage.code in ('03','04', '16') and c.status <> 'Failed' order by " + "createdDate desc")
        }
        if ("alreadyCS" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.stage.code in ('05','06', '07') and c.status <> 'Failed' order by " + "createdDate desc")
        }
        if ("alreadySP" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.stage.code in ('08','09','10') and c.status <> 'Failed' order by " + "createdDate desc")
        }
        if ("alreadyFD" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.stage.code = '11' and c.status <> 'Failed' order by createdDate desc")
        }
        if ("alreadySB" == stageStatus)
        {
            opportunity = Opportunity.findAll("from Opportunity as c where c.contact = " + contact.id + " and c.status = 'Failed' order by createdDate desc")
        }

        respond opportunity, model: [opportunityInstanceCount: opportunity.size(), stageStatus: stageStatus, contact: contact], view: "indexOfOpportunity"
    }

    /**
     *
     * 创建日期 2018-04-10
     * 创建人员 fc
     * 方法功能 精准估值上传青牛服务器时设置回调函数
     **/
    @Secured(['permitAll'])
    def getUploadToken()
    {
        def token = fileServerService.getUploadTokenPrecise("portalForApp/CallbackByQiniuPrecise")
        render([status: "success", token: token] as JSON)
        return
    }

    /**
     *
     * 创建日期 2018-04-10
     * 创建人员 fc
     * 方法功能 精准估值上传青牛服务器时设置回调函数
     **/
    @Secured(['permitAll'])
    def funQiniuPost()
    {
        //render([contactId: "1", type: "1",description:"Koala.jpg",fileName:"4zu8zs7fpcodetez207lnkfg6ian.jpg",city:"1"] as JSON)
        redirect(action: "CallbackByQiniuSuggest", params: [type: "1", "description": "Hydrangeas.jpg", "fileName": "zxl08ldrurvutryz63y0lua6d7ga.jpg"])
    }

    /**
     *
     * 创建日期 2018-04-18
     * 创建人员 fc
     * 方法功能 意见反馈上传青牛服务器时设置回调函数
     **/
    @Secured(['permitAll'])
    def getUploadTokenForSuggest()
    {
        def token = fileServerService.getUploadTokenSuggest("portalForApp/CallbackByQiniuSuggest")
        render([status: "success", token: token] as JSON)
        return
    }

    /**
     *
     * 创建日期 2018-03-23
     * 创建人员 fc
     * 方法功能 精准估值功能，页面二跳转
     **/
    @Secured('permitAll')
    @Transactional
    def CallbackByQiniuSuggest()
    {
        println "*********************** callbackByQiniu  ****************************"
        println params
        def json = request.JSON
        println "json:" + json
        /************************七牛服务器回调函数时返回json对象*****************************/
        String attachmentType = json["type"]
        String fileName = json["fileName"]
        String description = json['description']
        /****************************end*************************/
        /***********************自定义方法返回值使用params*****************************/
        //String attachmentType = params["type"]
        //String fileName = params["fileName"]
        //String description = params['description']
        /****************************end*************************/

        def attachment = new Attachments()
        attachment.fileName = "http://p66wk755l.bkt.clouddn.com/" + fileName
        attachment.thumbnailUrl = "http://p66wk755l.bkt.clouddn.com/" + fileName
        attachment.type = AttachmentType.findById(attachmentType)
        attachment.description = description.split('\\.')[0]

        println "*********************** end callbackByQiniu  ****************************"

        if (attachment.validate())
        {

            def files = []
            def sfile = [:]
            def o = [:]
            sfile['thumbnailUrl'] = attachment.thumbnailUrl
            sfile['name'] = description

            attachment.save flush: true

            sfile['fileid'] = attachment.id

            files.add(sfile)
            o['files'] = files

            render o as JSON
            return
        } else
        {
            println attachment.errors
            render([status: "error", errorMsg: "attachments save error"] as JSON)
            return
        }
    }

    /**
     *
     * 创建日期 2018-03-23
     * 创建人员 fc
     * 方法功能 公用错误页跳转页面
     **/
    @Secured('permitAll')
    def error()
    {
        return
    }

}
